package com.lc.zpyh.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.OnHttpListener;
import com.lc.zpyh.R;
import com.lc.zpyh.http.request.SetByCommodityIdAndNameApi;
import com.lc.zpyh.http.response.CondimentsQueryBean;
import com.lc.zpyh.http.response.SetByCommodityIdAndNameBean;
import com.lc.zpyh.http.response.SetByCommodityIdBean;
import com.lc.zpyh.util.BigDecimalUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.ButterKnife;

public class GoodsAttrDialog extends Dialog implements View.OnClickListener {
    private Context context;
    private ImageView close;
    private TextView tv_add_gouwuche,tv_attr1,tv_attr2,tv_total_money,tv_title01,tv_title02,tv_shop_name,tv_xiaoliao,tv_xiaoliao1;
    private RecyclerView rv_attr_one,rv_attr_two,rv_xiaoliao;
    List<SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean> dataAttrOneList = new ArrayList<>();
    List<SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean> dataAttrTwoList = new ArrayList<>();
    List<CondimentsQueryBean.ListBean> dataxiaoliaoList = new ArrayList<>();
//    小料名字
    private Map<Integer, String> specificationMap = new HashMap<>();
//小料价格
    private Map<Integer, String> goodsAttrMap = new HashMap<>();
//    小料id
    private Map<Integer, String> condimentsIdMap = new HashMap<>();

    private OnGoodsAttrListener onGoodsAttrListener;
    private String commdityId,commodityName,count;
    private BaseQuickAdapter<String, BaseViewHolder> arrtAdapter;
    private BaseQuickAdapter<SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean, BaseViewHolder> oneadapter;
    private BaseQuickAdapter<SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean, BaseViewHolder> twoadapter;
    private BaseQuickAdapter<CondimentsQueryBean.ListBean, BaseViewHolder> xiaoliaoadapter;
    private LinearLayout ll_xiaoliao,ll_guige02,ll_guige01;
    private String guige1;
    private String guige2;
    private String xiaoliao;
    private double xiaoliaoprice;
    private String condimentsId;
    private String guige1Id;
    private String name1;
    private String name2;
    private String cartId;
    private String countcart;
    private String guige2Id;
//    总规格的钱
    private String totalguigeprice="0";
//    总规格id
    private String totalguige;

    public GoodsAttrDialog(Context context,String name1 ,List<SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean> nameOnelist, String name2,List<SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean> nameTwolist, List<CondimentsQueryBean.ListBean> dataxiaoliaoList, String id,String commodityName,String count,String price,String cartId,String countcart) {
        super(context, R.style.dialog);
        this.context = context;
        this.dataAttrOneList=nameOnelist;
        this.dataAttrTwoList=nameTwolist;
        this.dataxiaoliaoList=dataxiaoliaoList;
        this.commdityId=id;
        this.commodityName=commodityName;
        this.name1 = name1;
        this.name2 = name2;
        this.totalguigeprice = price;
        this.count = count;
        this.cartId = cartId;
        this.countcart = countcart;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        Window window = getWindow();
        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置为居中
//        window.setWindowAnimations(R.style.bottom_menu_animation); // 添加动画效果
        setContentView(R.layout.dialog_goodsattr);
        WindowManager windowManager = ((Activity) context).getWindowManager();
//        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width = (int) (d.widthPixels * 0.8);
        getWindow().setAttributes(lp);
        setCanceledOnTouchOutside(false);// 点击Dialog外部消失



        initView();


    }
    private void initView() {
        tv_total_money = findViewById(R.id.tv_total_money);

        tv_attr1 = findViewById(R.id.tv_attr1);
        tv_attr2 = findViewById(R.id.tv_attr2);
        tv_shop_name = findViewById(R.id.tv_shop_name);

        tv_title02 = findViewById(R.id.tv_title02);
        tv_title01 = findViewById(R.id.tv_title01);
        rv_attr_one = findViewById(R.id.rv_attr_one);
        rv_attr_two = findViewById(R.id.rv_attr_two);
        rv_xiaoliao= findViewById(R.id.rv_xiaoliao);
        tv_xiaoliao= findViewById(R.id.tv_xiaoliao);
        tv_xiaoliao1= findViewById(R.id.tv_xiaoliao1);
        ll_xiaoliao = findViewById(R.id.ll_xiaoliao);
        ll_guige02 = findViewById(R.id.ll_guige02);
        ll_guige01 = findViewById(R.id.ll_guige01);

        close = findViewById(R.id.img_close);
        tv_add_gouwuche = findViewById(R.id.tv_add_gouwuche);
        tv_add_gouwuche.setOnClickListener(this);
        close.setOnClickListener(this);
        tv_shop_name.setText(commodityName);
        tv_title01.setText(name1);
        tv_total_money.setText("￥"+BigDecimalUtils.div(totalguigeprice,"100",2));
        /**
         * 小料列表
         */
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(RecyclerView.HORIZONTAL);

        rv_xiaoliao.setLayoutManager(manager);
        if (dataxiaoliaoList.size()>0) {
            ll_xiaoliao.setVisibility(View.VISIBLE);
            tv_xiaoliao.setVisibility(View.VISIBLE);
        }
        xiaoliaoadapter=new BaseQuickAdapter<CondimentsQueryBean.ListBean, BaseViewHolder>(R.layout.item_xiaoliao,dataxiaoliaoList) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, CondimentsQueryBean.ListBean listBean) {
                holder.setText(R.id.tv_xiaoliao, listBean.getTitle());
                if (listBean.isGrop()) {
                    holder.setTextColorRes(R.id.tv_xiaoliao, R.color.colorE46006);

                }else {
                    holder.setTextColorRes(R.id.tv_xiaoliao, R.color.color666666);
                }

            }
        } ;

       xiaoliaoadapter.setOnItemClickListener(new OnItemClickListener() {
           @RequiresApi(api = Build.VERSION_CODES.N)
           @Override
           public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
//               for (CondimentsQueryBean.ListBean bean :dataxiaoliaoList){
//                   bean.setGrop(false);
//               }
               CondimentsQueryBean.ListBean bean = dataxiaoliaoList.get(position);
               List<CondimentsQueryBean.ListBean> goodsAttrBeanList = dataxiaoliaoList;
                        if (goodsAttrBeanList != null && goodsAttrBeanList.size() > 0) {
                            for (int i = 0; i < dataxiaoliaoList.size(); i++) {
                                if (i == position) {
                                    boolean isSelect = goodsAttrBeanList.get(i).isGrop();
                                    goodsAttrBeanList.get(i).setGrop(!isSelect);
                                }
                            }
                        }
//               bean.setGrop(!bean.isGrop());
               xiaoliao = dataxiaoliaoList.get(position).getTitle();
               xiaoliaoprice = dataxiaoliaoList.get(position).getPrice();
               condimentsId = dataxiaoliaoList.get(position).getCondimentsId()+"";
               if (bean.isGrop()){

                specificationMap.put(position, xiaoliao);
                   goodsAttrMap.put(position, xiaoliaoprice+"");
                   condimentsIdMap.put(position, condimentsId+"");
               }else {
                specificationMap.remove(position, xiaoliao);
                   goodsAttrMap.remove(position, xiaoliaoprice+"");
                   condimentsIdMap.remove(position, condimentsId+"");
               }
               String specification = "";
               for (Integer key : specificationMap.keySet()) {
                   specification = specification + specificationMap.get(key) + "、";
               }
               xiaoliaoID();
               xiaoliaoprice();
               Log.e("TAG", "onItemClick: "+specification );
               tv_xiaoliao1.setText(specification);
               tv_total_money .setText("￥"+BigDecimalUtils.add(BigDecimalUtils.div(totalguigeprice,"100",2),BigDecimalUtils.div(xiaoliaoprice()+"","100",2),2));
               xiaoliaoadapter.notifyDataSetChanged();
           }
       });
        rv_xiaoliao.setAdapter(xiaoliaoadapter);

        /**
         * 规格一列表
         */
        if (dataAttrOneList!=null&&dataAttrOneList.size()>0) {
            ll_guige01.setVisibility(View.VISIBLE);
            FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
            layoutManager.setFlexDirection(FlexDirection.ROW);
            layoutManager.setJustifyContent(JustifyContent.FLEX_START);
            rv_attr_one.setLayoutManager(layoutManager);
            dataAttrOneList.get(0).setIstrue(true);
            tv_attr1.setText(dataAttrOneList.get(0).getSpecificationName() + "、");
            guige1 = dataAttrOneList.get(0).getSpecificationName();
            guige1Id = dataAttrOneList.get(0).getSpecificationId() + "";
            oneadapter = new BaseQuickAdapter<SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean, BaseViewHolder>(R.layout.item_shop_attr_rv, dataAttrOneList) {
                @Override
                protected void convert(BaseViewHolder holder, SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean bean) {
                    holder.setText(R.id.tv_attr, bean.getSpecificationName());
                    if (bean.isIstrue()) {
                        holder.setBackgroundResource(R.id.tv_attr, R.drawable.bg_attr_juhuang);
                        holder.setTextColorRes(R.id.tv_attr, R.color.white);
                        guige1 = bean.getSpecificationName();
                        guige1Id = bean.getSpecificationId() + "";
                    } else {
                        holder.setTextColorRes(R.id.tv_attr, R.color.color333333);
                        holder.setBackgroundResource(R.id.tv_attr, R.drawable.bg_attr_hui);
                    }
                }
            };
            oneadapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                    for (SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean bean : dataAttrOneList) {
                        bean.setIstrue(false);
                    }
                    SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean bean = dataAttrOneList.get(position);
                    bean.setIstrue(!bean.isIstrue());
                    if (bean.isIstrue()) {
                        guige1 = dataAttrOneList.get(position).getSpecificationName();
                        guige1Id = dataAttrOneList.get(position).getSpecificationId() + "";
                        tv_attr1.setText(guige1);
                        setByCommodityIdAndName();
                    }
                    oneadapter.notifyDataSetChanged();
                }
            });
            rv_attr_one.setAdapter(oneadapter);
        }
/**
 * 规格二列表
 */

        if (dataAttrTwoList!=null&&dataAttrTwoList.size()>0) {
                ll_guige02.setVisibility(View.VISIBLE);
                tv_title02.setText(name2);
                dataAttrTwoList.get(0).setIstrue(true);
            tv_attr2.setText(dataAttrTwoList.get(0).getSpecificationName());
            guige2=dataAttrTwoList.get(0).getSpecificationName();
            guige2Id = dataAttrTwoList.get(0).getSpecificationId()+"";
                FlexboxLayoutManager layoutManager01 = new FlexboxLayoutManager(context);
                layoutManager01.setFlexDirection(FlexDirection.ROW);
                layoutManager01.setJustifyContent(JustifyContent.FLEX_START);
                rv_attr_two.setLayoutManager(layoutManager01);
                twoadapter = new BaseQuickAdapter<SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean, BaseViewHolder>(R.layout.item_shop_attr_rv, dataAttrTwoList) {
                    @Override
                    protected void convert(BaseViewHolder holder, SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean bean) {
                        holder.setText(R.id.tv_attr, bean.getSpecificationName());
                        if (bean.isIstrue()) {
                            holder.setBackgroundResource(R.id.tv_attr, R.drawable.bg_attr_juhuang);
                            holder.setTextColorRes(R.id.tv_attr, R.color.white);
                            guige2 = bean.getSpecificationName();
                            guige2Id = bean.getSpecificationId()+"";
                        }else {
                            holder.setBackgroundResource(R.id.tv_attr, R.drawable.bg_attr_hui);
                            holder.setTextColorRes(R.id.tv_attr, R.color.color333333);
                        }

//
                    }
                };
                rv_attr_two.setAdapter(twoadapter);
                twoadapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                        for (SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean bean :dataAttrTwoList){
                            bean.setIstrue(false);
                        }
                        SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean bean = dataAttrTwoList.get(position);
                        bean.setIstrue(!bean.isIstrue());
                        if (bean.isIstrue()){
                            guige2= dataAttrTwoList.get(position).getSpecificationName();
                            guige2Id= dataAttrTwoList.get(position).getSpecificationId()+"";
                            tv_attr2.setText(guige2+"、");
                            setByCommodityIdAndName();
                        }
                        twoadapter.notifyDataSetChanged();
                    }
                });
            }
        setByCommodityIdAndName();




    }

    private String xiaoliaoID() {
        String condimentsId= "";
        if (condimentsIdMap.size()>0) {
            for (Integer key : condimentsIdMap.keySet()) {
                condimentsId = condimentsId + condimentsIdMap.get(key) + ",";
            }
        }
        return condimentsId;
    }

    private String xiaoliaoprice() {
        String goodsAttr = "0";
        if (goodsAttrMap.size()>0) {
            for (Integer key : goodsAttrMap.keySet()) {
                goodsAttr = BigDecimalUtils.add(goodsAttr, goodsAttrMap.get(key), 2);
            }
        }
        return goodsAttr;
    }

    private void setByCommodityIdAndName() {
        EasyHttp.post(new ApplicationLifecycle())
                .api(new SetByCommodityIdAndNameApi().setCommdityId(commdityId).setIdOne(guige1Id).setIdTwo(guige2Id)).request(new OnHttpListener<SetByCommodityIdAndNameBean>() {

            @Override
            public void onSucceed(SetByCommodityIdAndNameBean data) {
                if (data.getCode()==0){
                    if (data.getList()!=null) {
                        totalguigeprice = data.getList().getPrice() + "";
                        totalguige = data.getList().getId() + "";
                        tv_total_money .setText("￥"+BigDecimalUtils.add(BigDecimalUtils.div(totalguigeprice,"100",2),BigDecimalUtils.div(xiaoliaoprice()+"","100",2),2));
                    }
                }
            }
            @Override
            public void onFail(Exception e) {


            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add_gouwuche:

                if (onGoodsAttrListener != null) {
                    onGoodsAttrListener.onAddShoppingCart(commdityId,"1",totalguige,BigDecimalUtils.add(totalguigeprice,xiaoliaoprice(),0),xiaoliaoID(),cartId,countcart);
                    dismiss();
                }
                break;
            case R.id.img_close:
if (onGoodsAttrListener != null){
    onGoodsAttrListener.dissmiss();
}
                dismiss();
                break;



            default:
                break;
        }
    }
    public interface OnGoodsAttrListener {


        void onAddShoppingCart(String id,String count,String specificationId,String price,String condimentsId,String cartId,String countcart);

        void dissmiss();



    }

    public void setOnGoodsAttrListener(OnGoodsAttrListener onGoodsAttrListener) {
        this.onGoodsAttrListener = onGoodsAttrListener;
    }
}
